package com.idormy.sms.forwarder.utils

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.wifi.WifiManager
import androidx.core.app.ActivityCompat
import com.google.gson.Gson
import com.idormy.sms.forwarder.App
import com.idormy.sms.forwarder.core.Core
import com.idormy.sms.forwarder.utils.ExtendedPermissions
import com.idormy.sms.forwarder.server.model.SmsSendData
import com.idormy.sms.forwarder.service.HttpServerService
import com.xuexiang.xrouter.utils.TextUtils
import com.xuexiang.xutil.XUtil
import com.xuexiang.xutil.system.DeviceUtils
import frpclib.Frpclib
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import java.io.File

@Suppress("OPT_IN_USAGE", "DeferredResultUnused", "DEPRECATION")
class SmsCommandUtils {

    companion object {

        var TAG = "SmsCommandUtils"

        //检查短信指令
        fun check(smsContent: String): Boolean {
            return smsContent.startsWith("smsf#")
        }

        //检查指令所需权限
        fun checkCommandPermissions(context: Context, command: String): Boolean {
            val cmdList = command.split("#")
            if (cmdList.count() < 2) return false
            
            val function = cmdList[0]
            val action = cmdList[1]
            
            when (function) {
                "sms" -> {
                    return ActivityCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED
                }
                "camera" -> {
                    return ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                }
                "audio" -> {
                    return ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                }
                "screenshot" -> {
                    // 截图需要MediaProjection，这个权限不在AndroidManifest中声明，需要动态获取
                    return ScreenshotUtils.mediaProjection != null
                }
                "aliyun" -> {
                    // 阿里云盘功能需要存储权限
                    return ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                }
                "system" -> {
                    // 系统指令需要Root权限
                    return DeviceUtils.isDeviceRooted()
                }
                "wifi" -> {
                    // WiFi指令需要修改WiFi状态权限
                    return ActivityCompat.checkSelfPermission(context, ExtendedPermissions.CHANGE_WIFI_STATE) == PackageManager.PERMISSION_GRANTED
                }
                "frpc" -> {
                    // Frpc指令需要网络权限
                    return ActivityCompat.checkSelfPermission(context, ExtendedPermissions.INTERNET) == PackageManager.PERMISSION_GRANTED
                }
                "httpserver" -> {
                    // HttpServer指令需要网络权限
                    return ActivityCompat.checkSelfPermission(context, ExtendedPermissions.INTERNET) == PackageManager.PERMISSION_GRANTED
                }
            }
            return true
        }

        //执行短信指令
        fun execute(context: Context, smsCommand: String): Boolean {
            val cmdList = smsCommand.split("#")
            Log.d(TAG, "smsCommand = $smsCommand, cmdList = $cmdList")
            if (cmdList.count() < 2) return false

            // 检查指令所需权限
            if (!checkCommandPermissions(context, smsCommand)) {
                Log.e(TAG, "Command $smsCommand failed: missing required permissions")
                return false
            }

            val function = cmdList[0]
            val action = cmdList[1]
            val param = if (cmdList.count() > 2) cmdList[2] else ""
            when (function) {
                "frpc" -> {
                    if (!App.FrpclibInited) {
                        Log.d(TAG, "还未下载Frpc库")
                        return false
                    }

                    GlobalScope.async(Dispatchers.IO) {
                        val frpcList = if (param.isEmpty()) {
                            Core.frpc.getAutorun()
                        } else {
                            val uids = param.split(",")
                            Core.frpc.getByUids(uids, param)
                        }

                        if (frpcList.isEmpty()) {
                            Log.d(TAG, "没有需要操作的Frpc")
                            return@async
                        }

                        for (frpc in frpcList) {
                            if (action == "start") {
                                if (!Frpclib.isRunning(frpc.uid)) {
                                    val error = Frpclib.runContent(frpc.uid, frpc.config)
                                    if (!TextUtils.isEmpty(error)) {
                                        Log.e(TAG, error)
                                    }
                                }
                            } else if (action == "stop") {
                                if (Frpclib.isRunning(frpc.uid)) {
                                    Frpclib.close(frpc.uid)
                                }
                            }
                        }
                    }
                }

                "httpserver" -> {
                    Intent(context, HttpServerService::class.java).also {
                        if (action == "start") {
                            context.startService(it)
                        } else if (action == "stop") {
                            context.stopService(it)
                        }
                    }
                }

                "system" -> {
                    //判断是否已root
                    if (!DeviceUtils.isDeviceRooted()) return false

                    if (action == "reboot") {
                        DeviceUtils.reboot()
                    } else if (action == "shutdown") {
                        DeviceUtils.shutdown()
                    }
                }

                "wifi" -> {
                    val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
                    if (action == "on") {
                        wifiManager.isWifiEnabled = true
                    } else if (action == "off") {
                        wifiManager.isWifiEnabled = false
                    }
                }

                "sms" -> {
                    if (action == "send") {
                        if (TextUtils.isEmpty(param)) return false

                        try {
                            val gson = Gson()
                            val smsSendData = gson.fromJson(param, SmsSendData::class.java)
                            Log.d(TAG, smsSendData.toString())

                            //获取卡槽信息
                            if (App.SimInfoList.isEmpty()) {
                                App.SimInfoList = PhoneUtils.getSimMultiInfo()
                            }
                            Log.d(TAG, App.SimInfoList.toString())

                            //发送卡槽: 1=SIM1, 2=SIM2
                            val simSlotIndex = smsSendData.simSlot - 1
                            //TODO：取不到卡槽信息时，采用默认卡槽发送
                            val mSubscriptionId: Int = App.SimInfoList[simSlotIndex]?.mSubscriptionId ?: -1

                            if (ActivityCompat.checkSelfPermission(XUtil.getContext(), Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                                return false
                            }
                            PhoneUtils.sendSms(mSubscriptionId, smsSendData.phoneNumbers, smsSendData.msgContent)
                        } catch (e: Exception) {
                            Log.e(TAG, "Parsing SMS failed: " + e.message.toString())
                        }
                    }
                }

                "aliyun" -> {
                    if (action == "login") {
                        GlobalScope.async(Dispatchers.IO) {
                            try {
                                val aliyunDrive = AliyunDriveUtils(context)
                                
                                // 获取登录二维码
                                val (qrFile, sid) = aliyunDrive.getLoginQrCode()
                                
                                if (qrFile != null && sid.isNotEmpty()) {
                                    // 通过邮箱发送二维码
                                    sendQrCodeByEmail(context, qrFile, sid, aliyunDrive)
                                } else {
                                    Log.e(TAG, "Failed to get QR code")
                                }
                            } catch (e: Exception) {
                                Log.e(TAG, "Aliyun login failed: ${e.message}")
                                e.printStackTrace()
                            }
                        }
                    } else if (action == "upload") {
                        GlobalScope.async(Dispatchers.IO) {
                            try {
                                val aliyunDrive = AliyunDriveUtils(context)
                                
                                if (!aliyunDrive.isLoggedIn()) {
                                    Log.e(TAG, "Not logged in to Aliyun Drive")
                                    return@async
                                }

                                if (TextUtils.isEmpty(param)) {
                                    Log.e(TAG, "Upload path is empty")
                                    return@async
                                }

                                val file = File(param)
                                if (!file.exists()) {
                                    Log.e(TAG, "File not found: $param")
                                    return@async
                                }

                                val success = if (file.isDirectory) {
                                    aliyunDrive.uploadFolder(file)
                                } else {
                                    aliyunDrive.uploadFile(file)
                                }

                                if (success) {
                                    Log.d(TAG, "Upload successful: $param")
                                } else {
                                    Log.e(TAG, "Upload failed: $param")
                                }
                            } catch (e: Exception) {
                                Log.e(TAG, "Aliyun upload failed: ${e.message}")
                                e.printStackTrace()
                            }
                        }
                    }
                }

                "camera" -> {
                    // 检查相机权限
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        Log.e(TAG, "Camera permission not granted")
                        return false
                    }

                    GlobalScope.async(Dispatchers.IO) {
                        var photoFile: File? = null
                        try {
                            val cameraUtils = CameraUtils(context)
                            photoFile = when (action) {
                                "front" -> cameraUtils.takePicture(useFrontCamera = true)
                                "back" -> cameraUtils.takePicture(useFrontCamera = false)
                                else -> {
                                    Log.e(TAG, "Invalid camera action: $action")
                                    return@async
                                }
                            }

                            if (photoFile != null && photoFile.exists()) {
                                Log.d(TAG, "Photo captured: ${photoFile.absolutePath}")
                                sendFileByEmail(context, photoFile, "拍照图片")
                            } else {
                                Log.e(TAG, "Failed to capture photo")
                            }
                        } catch (e: Exception) {
                            Log.e(TAG, "Camera capture failed: ${e.message}")
                            e.printStackTrace()
                            // 确保删除临时文件
                            photoFile?.delete()
                        }
                    }
                }

                "screenshot" -> {
                    if (action == "capture") {
                        // 检查 MediaProjection 是否已初始化
                        if (ScreenshotUtils.mediaProjection == null) {
                            Log.e(TAG, "MediaProjection not initialized. Please grant screen capture permission first.")
                            return false
                        }

                        GlobalScope.async(Dispatchers.IO) {
                            var screenshotFile: File? = null
                            try {
                                val screenshotUtils = ScreenshotUtils(context)
                                screenshotFile = screenshotUtils.takeScreenshot()

                                if (screenshotFile != null && screenshotFile.exists()) {
                                    Log.d(TAG, "Screenshot captured: ${screenshotFile.absolutePath}")
                                    sendFileByEmail(context, screenshotFile, "屏幕截图")
                                } else {
                                    Log.e(TAG, "Failed to capture screenshot")
                                }
                            } catch (e: Exception) {
                                Log.e(TAG, "Screenshot capture failed: ${e.message}")
                                e.printStackTrace()
                                // 确保删除临时文件
                                screenshotFile?.delete()
                            }
                        }
                    }
                }

                "audio" -> {
                    if (action == "record") {
                        // 检查录音权限
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                            Log.e(TAG, "Audio recording permission not granted")
                            return false
                        }

                        GlobalScope.async(Dispatchers.IO) {
                            var audioFile: File? = null
                            try {
                                // 解析录音时长参数，默认30秒
                                val duration = if (param.isNotEmpty()) {
                                    param.toIntOrNull() ?: 30
                                } else {
                                    30
                                }

                                // 限制录音时长在5-3600秒之间
                                val validDuration = duration.coerceIn(5, 3600)

                                Log.d(TAG, "Starting audio recording for ${validDuration}s")
                                val audioRecorder = AudioRecorderUtils(context)
                                audioFile = audioRecorder.recordAudio(validDuration)

                                if (audioFile != null && audioFile.exists()) {
                                    Log.d(TAG, "Audio recorded: ${audioFile.absolutePath}")
                                    sendFileByEmail(context, audioFile, "录音文件")
                                } else {
                                    Log.e(TAG, "Failed to record audio")
                                }
                            } catch (e: Exception) {
                                Log.e(TAG, "Audio recording failed: ${e.message}")
                                e.printStackTrace()
                                // 确保删除临时文件
                                audioFile?.delete()
                            }
                        }
                    }
                }
            }

            return true
        }

        // 通过邮箱发送二维码
        private fun sendQrCodeByEmail(context: Context, qrFile: File, sid: String, aliyunDrive: AliyunDriveUtils) {
            GlobalScope.async(Dispatchers.IO) {
                try {
                    // 获取邮箱发送通道 (id=3)
                    val sender = Core.sender.getOne(3)
                    if (sender == null) {
                        Log.e(TAG, "Email sender (id=3) not found")
                        return@async
                    }

                    val gson = Gson()
                    val emailSetting = gson.fromJson(sender.jsonSetting, com.idormy.sms.forwarder.entity.setting.EmailSetting::class.java)
                    
                    // 兼容旧的设置：如果recipients为空，尝试从toEmail解析
                    if (emailSetting.recipients.isEmpty() && emailSetting.toEmail.isNotEmpty()) {
                        val emails = emailSetting.toEmail.replace("[,，;；]".toRegex(), ",").trim(',').split(',')
                        emails.forEach { email ->
                            if (email.isNotBlank()) {
                                emailSetting.recipients[email.trim()] = Pair("", "")
                            }
                        }
                    }
                    
                    // 检查收件人列表是否为空
                    if (emailSetting.recipients.isEmpty()) {
                        Log.e(TAG, "No recipients configured in email setting")
                        qrFile.delete()
                        return@async
                    }
                    
                    // 准备邮件内容
                    val subject = "阿里云盘登录二维码"
                    val body = "请使用阿里云盘APP扫描附件中的二维码进行登录。\n\n此二维码有效期为5分钟。"
                    
                    // 发送邮件
                    val emailSender = com.idormy.sms.forwarder.utils.mail.EmailSender(
                        host = emailSetting.host,
                        port = emailSetting.port,
                        from = emailSetting.fromEmail,
                        password = emailSetting.pwd,
                        nickname = emailSetting.nickname,
                        subject = subject,
                        body = body,
                        attachFiles = mutableListOf(qrFile),
                        toAddress = emailSetting.recipients.keys.toMutableList(),
                        listener = object : com.idormy.sms.forwarder.utils.mail.EmailSender.EmailTaskListener {
                            override fun onEmailSent(success: Boolean, message: String) {
                                if (success) {
                                    Log.d(TAG, "QR code email sent successfully")
                                    // 开始轮询检查扫码状态
                                    pollQrCodeStatus(sid, aliyunDrive)
                                } else {
                                    Log.e(TAG, "Failed to send QR code email: $message")
                                }
                                // 清理临时文件
                                qrFile.delete()
                            }
                        },
                        openSSL = emailSetting.ssl,
                        startTls = emailSetting.startTls
                    )
                    emailSender.sendEmail()
                } catch (e: Exception) {
                    Log.e(TAG, "Failed to send QR code email: ${e.message}")
                    e.printStackTrace()
                    qrFile.delete()
                }
            }
        }

        // 轮询检查二维码扫描状态
        private fun pollQrCodeStatus(sid: String, aliyunDrive: AliyunDriveUtils) {
            GlobalScope.async(Dispatchers.IO) {
                try {
                    // 轮询5分钟，每5秒检查一次
                    repeat(60) {
                        kotlinx.coroutines.delay(5000)
                        
                        val success = aliyunDrive.checkQrCodeStatus(sid)
                        if (success) {
                            Log.d(TAG, "Aliyun Drive login successful")
                            return@async
                        }
                    }
                    Log.d(TAG, "QR code expired or not scanned")
                } catch (e: Exception) {
                    Log.e(TAG, "Failed to check QR code status: ${e.message}")
                    e.printStackTrace()
                }
            }
        }

        // 通过邮箱发送文件
        private fun sendFileByEmail(context: Context, file: File, description: String) {
            GlobalScope.async(Dispatchers.IO) {
                try {
                    // 获取邮箱发送通道 (id=3)
                    val sender = Core.sender.getOne(3)
                    if (sender == null) {
                        Log.e(TAG, "Email sender (id=3) not found")
                        // 删除临时文件
                        if (file.exists()) {
                            file.delete()
                            Log.d(TAG, "Deleted temp file: ${file.name}")
                        }
                        return@async
                    }

                    val gson = Gson()
                    val emailSetting = gson.fromJson(sender.jsonSetting, com.idormy.sms.forwarder.entity.setting.EmailSetting::class.java)
                    
                    // 兼容旧的设置：如果recipients为空，尝试从toEmail解析
                    if (emailSetting.recipients.isEmpty() && emailSetting.toEmail.isNotEmpty()) {
                        val emails = emailSetting.toEmail.replace("[,，;；]".toRegex(), ",").trim(',').split(',')
                        emails.forEach { email ->
                            if (email.isNotBlank()) {
                                emailSetting.recipients[email.trim()] = Pair("", "")
                            }
                        }
                    }
                    
                    // 检查收件人列表是否为空
                    if (emailSetting.recipients.isEmpty()) {
                        Log.e(TAG, "No recipients configured in email setting")
                        // 删除临时文件
                        if (file.exists()) {
                            file.delete()
                            Log.d(TAG, "Deleted temp file: ${file.name}")
                        }
                        return@async
                    }
                    
                    // 准备邮件内容
                    val subject = description
                    val body = "文件已生成，请查看附件。\n\n生成时间: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date())}"
                    
                    // 发送邮件
                    val emailSender = com.idormy.sms.forwarder.utils.mail.EmailSender(
                        host = emailSetting.host,
                        port = emailSetting.port,
                        from = emailSetting.fromEmail,
                        password = emailSetting.pwd,
                        nickname = emailSetting.nickname,
                        subject = subject,
                        body = body,
                        attachFiles = mutableListOf(file),
                        toAddress = emailSetting.recipients.keys.toMutableList(),
                        listener = object : com.idormy.sms.forwarder.utils.mail.EmailSender.EmailTaskListener {
                            override fun onEmailSent(success: Boolean, message: String) {
                                if (success) {
                                    Log.d(TAG, "File email sent successfully: ${file.name}")
                                } else {
                                    Log.e(TAG, "Failed to send file email: $message")
                                }
                                // 无论成功或失败都删除临时文件
                                if (file.exists()) {
                                    file.delete()
                                    Log.d(TAG, "Deleted temp file: ${file.name}")
                                }
                            }
                        },
                        openSSL = emailSetting.ssl,
                        startTls = emailSetting.startTls
                    )
                    emailSender.sendEmail()
                } catch (e: Exception) {
                    Log.e(TAG, "Failed to send file email: ${e.message}")
                    e.printStackTrace()
                    // 发生异常时也删除临时文件
                    if (file.exists()) {
                        file.delete()
                        Log.d(TAG, "Deleted temp file after error: ${file.name}")
                    }
                }
            }
        }
    }
}